import store from './store'
import router from './router'
import Cookies from 'js-cookie'
import { findMenuByMerchant } from './api'
import Vue from 'vue'

// 递归拿到当前当前数组的叶子节点(叶子节点为权限判断点)
function getPower (arry) {
    if (arry.length > 0) {
        for (const i in arry) {
            if (arry[i].title == store.state.asideActive) {
                store.commit("SET_POWER", arry[i].children);
                break;
            } else {
                if (arry[i].children) {
                    getPower(arry[i].children)
                }
            }
        }
    }
}

function Alert () {
    Cookies.remove(process.env.COOKIE_NAME + "_companyName");
    Cookies.remove(process.env.COOKIE_NAME + "_isFirstLogin");
    Cookies.remove(process.env.COOKIE_NAME + "_isShop");
    Cookies.remove(process.env.COOKIE_NAME + "_linkName");
    Cookies.remove(process.env.COOKIE_NAME + "_merchantId");
    Cookies.remove(process.env.COOKIE_NAME + "_token");
    Cookies.remove(process.env.COOKIE_NAME + "_userInfo");
    Cookies.remove(process.env.COOKIE_NAME + "_isOwnAuth");
    Cookies.remove(process.env.COOKIE_NAME + "_businessScope");
    Vue.prototype.$alert('用户还未被分配权限,请提示管理员及时为您分配功能权限', '提示', {
        confirmButtonText: '确定',
        callback: () => {
            location.reload()
        }
    });
}

var arr = [], // 拆分后的数据集
    leafArr = [], // 叶子节点
    stemArr = [], // 枝干节点
    newLeafArr = [], // 去掉无权限小集合的叶子节点
    itemArr = []; // 所有需要用到的itemArr
// 拆分树
function setArr (tree) {
    arr = arr.concat(tree)
    if (tree.children && tree.children[0]) {
        for (let i = 0; i < tree.children.length; i++) {
            setArr(tree.children[i])
        }
    }
}
// 获得新树要用的item数组
function getNewArr (params) {
    for (let i = 0; i < params.length; i++) {
        for (let k = 0; k < arr.length; k++) {
            if (params[i].pid == arr[k].id) {
                itemArr.push(arr[k])
                if (arr[k].pid != 0) {
                    getNewArr([arr[k]])
                }
            }
        }

    }
}

// 拼接树
function setTreeData (source) {
    let cloneData = JSON.parse(JSON.stringify(source))
    let tree = cloneData.filter(father => {
        let branchArr = cloneData.filter(child => {
            return father.id == child.pid
        });
        if (branchArr.length > 0) {
            father.children = branchArr;
        }
        return father.pid == 0;
    });
    return tree
}
const whiteList = ['/login'] // 不重定向白名单
router.beforeEach((to, from, next) => {
    // 查token是否存在
    if (store.getters.token) {
        // 个人信息不存在时存入个人信息
        if (store.state.userId == undefined) {
            let userInfo = JSON.parse(Cookies.get(process.env.COOKIE_NAME + '_userInfo'))
            store.commit("SET_USERID", userInfo.userId);
            store.commit("SET_HEADURL", userInfo.headUrl);
            store.commit("SET_USERNAME", userInfo.userName);
            store.commit("SET_MOBILE", userInfo.mobile);
        }
        // token存在时 去登陆页帮着重定向到内容页
        if (to.path === '/login') {
            next({ path: '/' })
        } else if (to.path === '/application/entry-application') {
            next()
        } else if (to.path === '/home/select-model') {
            next()
        } else if (to.path === '/application/business-claim') {
            next()
        } else if (to.path === '/home/personal-center' && store.state.merchantId == undefined) {
            next()
        } else {
            var data = {
                token: store.state.token,
                userId: store.state.userId,
                merchantId: store.state.merchantId
            }
            // 如果菜单树不存在
            if (store.state.privilegeTree == undefined) {
                findMenuByMerchant(data).then(res => {
                    arr = [] // 拆分后的数据集
                    leafArr = [] // 叶子节点
                    stemArr = [] // 枝干节点
                    newLeafArr = [] // 去掉无权限小集合的叶子节点
                    itemArr = [] // 所有需要用到的itemArr
                    if (res.code == 200) {
                        if (res.data.menuList.length > 0) {
                            // 处理菜单树 打散重构
                            for (let i = 0; i < res.data.menuList.length; i++) {
                                setArr(res.data.menuList[i])
                            }
                        }
                        // 拆分后的数据集 将所有的节点的children节点去掉 避免垃圾数据
                        arr.forEach(function (item) {
                            delete item.children;
                        })
                        // 拆分后的数据集中的所有叶子节点拿出来 放入leafArr
                        for (let i = 0; i < arr.length; i++) {
                            if (arr[i].isLeafnode == 0) {
                                leafArr.push(arr[i])
                            } else {
                                // 将枝干节点拿出来放入stemArr
                                stemArr.push(arr[i])
                            }
                        }
                        // 父级相同的放一个小集合 然后排除掉没有查看权限的小集合
                        stemArr.filter(father => {
                            let smallArr = leafArr.filter(child => {
                                return father.id == child.pid
                            });
                            if (smallArr.length > 0) {
                                for (let i = 0; i < smallArr.length; i++) {
                                    if (smallArr[i].title == '查看') {
                                        newLeafArr = newLeafArr.concat(smallArr)
                                    }
                                }
                            }
                        });
                        // 拿到子节点 放入itemArr 从子节点反向递归 获得整个树要用到的所有对象
                        itemArr = newLeafArr
                        getNewArr(newLeafArr)
                        // 数组去重
                        var set = new Set(itemArr);
                        var newArr = Array.from(set);
                        var menuList = setTreeData(newArr)
                        // 菜单树
                        for (let i = 0; i < menuList.length; i++) {
                            if (menuList[i].title == '个人中心') {
                                menuList.splice(i, 1);
                            }
                        }
                        if (menuList.length == 0) {
                            next('/home/personal-center')
                        }
                        store.commit("SET_PRIVILEGETREE", menuList);
                        if (to.path === '/') {
                            // 当前页面为菜单树第一个
                            store.commit("SET_CURRENTPAGE", menuList[0].title);
                            // 侧边栏菜单为1级
                            if (menuList[0].children[0].children[0].isLeafnode == 0) {
                                store.commit("SET_SUB", false);
                                // 默认当前侧边
                                store.commit("SET_DEFAULTASIDEACTIVE", menuList[0].children[0].title);
                                // 打开当前的侧边
                                store.commit("SET_ASIDEACTIVE", menuList[0].children[0].title);
                                if (!menuList[0].children[0].menuUrl) {
                                    Alert()
                                } else {
                                    router.replace(menuList[0].children[0].menuUrl)
                                }
                            } else { // 侧边栏菜单为2级
                                store.commit("SET_SUB", true);
                                // 默认当前侧边
                                store.commit("SET_DEFAULTASIDEACTIVE", menuList[0].children[0].children[0].title);
                                // 打开当前的侧边
                                store.commit("SET_ASIDEACTIVE", menuList[0].children[0].children[0].title);
                                if (!menuList[0].children[0].children[0].menuUrl) {
                                    Alert()
                                } else {
                                    router.replace(menuList[0].children[0].children[0].menuUrl)
                                }
                            }
                        } else {
                            // 当前进入页不是叶子节点
                            if (!to.meta.isSub) {
                                store.commit("SET_SUB", false);
                                // 默认当前侧边
                                store.commit("SET_DEFAULTASIDEACTIVE", to.name);
                                // 打开当前的侧边
                                store.commit("SET_ASIDEACTIVE", to.name);
                            } else {
                                // 当前进入页是叶子节点
                                store.commit("SET_SUB", true);
                                // 默认当前侧边
                                store.commit("SET_DEFAULTASIDEACTIVE", to.matched[to.matched.length - 2].name);
                                // 打开当前的侧边
                                store.commit("SET_ASIDEACTIVE", to.matched[to.matched.length - 2].name);
                            }
                            // 侧边栏选中的二级节点,根据二级节点找到此节点下的权限表
                            if (to.matched[1]) {
                                store.commit("SET_CURRENTPAGE", to.matched[1].name);
                                for (let i = 0; i < store.state.privilegeTree.length; i++) {
                                    if (store.state.privilegeTree[i].title == to.matched[1].name) {
                                        store.commit("SET_MENUINDEX", store.state.privilegeTree[i].children);
                                        getPower(store.state.menuIndex)
                                    }
                                }
                            }
                            next()
                        }
                    } else {
                        // Vue.prototype.$alert(res.msg, '提示', {
                        //     confirmButtonText: '确定',
                        //     callback: () => {
                                Cookies.remove(process.env.COOKIE_NAME + "_companyName");
                                Cookies.remove(process.env.COOKIE_NAME + "_isFirstLogin");
                                Cookies.remove(process.env.COOKIE_NAME + "_isShop");
                                Cookies.remove(process.env.COOKIE_NAME + "_linkName");
                                Cookies.remove(process.env.COOKIE_NAME + "_merchantId");
                                Cookies.remove(process.env.COOKIE_NAME + "_token");
                                Cookies.remove(process.env.COOKIE_NAME + "_userInfo");
                                Cookies.remove(process.env.COOKIE_NAME + "_soUrce");
                                Cookies.remove(process.env.COOKIE_NAME + "_isOwnAuth");
                                Cookies.remove(
                                    process.env.COOKIE_NAME + "_businessScope"
                                );
                                location.reload()
                        //     }
                        // });
                    }
                })
            } else {
                if (to.path === '/') {
                    var menuList = store.state.privilegeTree
                    // 当前页面为菜单树第一个
                    store.commit("SET_CURRENTPAGE", menuList[0].title);
                    // 侧边栏菜单为1级
                    if (menuList[0].children[0].children[0].isLeafnode == 0) {
                        store.commit("SET_SUB", false);
                        // 默认当前侧边
                        store.commit("SET_DEFAULTASIDEACTIVE", menuList[0].children[0].title);
                        // 打开当前的侧边
                        store.commit("SET_ASIDEACTIVE", menuList[0].children[0].title);
                        if (!menuList[0].children[0].menuUrl) {
                            Alert()
                        } else {
                            router.replace(menuList[0].children[0].menuUrl)
                        }
                    } else { // 侧边栏菜单为2级
                        store.commit("SET_SUB", true);
                        // 默认当前侧边
                        store.commit("SET_DEFAULTASIDEACTIVE", menuList[0].children[0].children[0].title);
                        // 打开当前的侧边
                        store.commit("SET_ASIDEACTIVE", menuList[0].children[0].children[0].title);
                        if (!menuList[0].children[0].children[0].menuUrl) {
                            Alert()
                        } else {
                            router.replace(menuList[0].children[0].children[0].menuUrl)
                        }
                    }
                } else if (!to.meta.isSub) { // 当前进入页不是叶子节点
                    store.commit("SET_SUB", false);
                    // 默认当前侧边
                    store.commit("SET_DEFAULTASIDEACTIVE", to.name);
                    // 打开当前的侧边
                    store.commit("SET_ASIDEACTIVE", to.name);
                } else {
                    // 当前进入页是叶子节点
                    store.commit("SET_SUB", true);
                    // 默认当前侧边
                    store.commit("SET_DEFAULTASIDEACTIVE", to.matched[to.matched.length - 2].name);
                    // 打开当前的侧边
                    store.commit("SET_ASIDEACTIVE", to.matched[to.matched.length - 2].name);
                }
                // 侧边栏选中的节点
                if (to.matched[1]) {
                    store.commit("SET_CURRENTPAGE", to.matched[1].name);
                    for (let i = 0; i < store.state.privilegeTree.length; i++) {
                        if (store.state.privilegeTree[i].title == to.matched[1].name) {
                            store.commit("SET_MENUINDEX", store.state.privilegeTree[i].children);
                            getPower(store.state.menuIndex)
                        }
                    }
                }
                next()
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
            next()
        } else {
            next('/login') // 否则全部重定向到登录页
        }
    }
})
